﻿using System;
using System.Collections.Generic;
using Web7.Ioc;
using Autofac;

namespace Web7.Core.IOC.Autofac
{
    public class AutofacResolver : IWeb7DependencyResolver
    {
        private readonly ILifetimeScope _container = null;

        internal AutofacResolver(ILifetimeScope container)
        {
            _container = container;
        }

        internal ILifetimeScope AutofacContainer
        {
            get { return _container; }
        }

        public T Resolve<T>()
        {
            return AutofacContainer.Resolve<T>();
        }

        public IEnumerable<T> ResolveAll<T>()
        {
            return AutofacContainer.Resolve<IEnumerable<T>>();
        }

        public T Resolve<T>(string name)
        {
            return AutofacContainer.ResolveNamed<T>(name);
        }

        public object Resolve(Type type)
        {
            return AutofacContainer.Resolve(type);
        }

        public IEnumerable<object> ResolveAll(Type type)
        {
            var enumerableServiceType = typeof(IEnumerable<>).MakeGenericType(type);
            var instance = AutofacContainer.Resolve(enumerableServiceType);

            return (IEnumerable<object>)instance;
        }

        public object Resolve(Type type, string name)
        {
            return AutofacContainer.ResolveNamed(name, type);
        }

        #region Implementation of IDisposable

        public void Dispose()
        {
            _container.Dispose();
        }

        #endregion
    }
}
